package com.synergy.stockflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.synergy.stockflow.entity.SysDictItem;
import com.synergy.stockflow.entity.SysDictType;
import com.synergy.stockflow.entity.bo.SysDictTypeQueryBO;
import com.synergy.stockflow.entity.vo.SysDictItemVO;
import com.synergy.stockflow.entity.vo.SysDictTypeVO;
import com.synergy.stockflow.mapper.SysDictItemMapper;
import com.synergy.stockflow.mapper.SysDictTypeMapper;
import com.synergy.stockflow.service.SysDictTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    private final SysDictItemMapper sysDictItemMapper;

    public SysDictTypeServiceImpl(SysDictItemMapper sysDictItemMapper) {
        this.sysDictItemMapper = sysDictItemMapper;
    }


    @Override
    public Page<SysDictTypeVO> pageByQuery(Page<SysDictType> page, SysDictTypeQueryBO query) {
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SysDictType::getTypeCode, query.getTypeCode());
        Page<SysDictType> typePage = baseMapper.selectPage(page, queryWrapper);
        List<SysDictTypeVO> vos = typePage.getRecords().stream().map(this::convert).collect(Collectors.toList());
        Page<SysDictTypeVO> voPage = new Page<>();
        voPage.setCurrent(typePage.getCurrent());
        voPage.setSize(typePage.getSize());
        voPage.setTotal(typePage.getTotal());
        voPage.setRecords(vos);
        return voPage;
    }

    private SysDictTypeVO convert(SysDictType type) {
        SysDictTypeVO vo = new SysDictTypeVO();
        BeanUtils.copyProperties(type, vo);
        vo.setDeleted(type.getDelFlag() != null && type.getDelFlag().equals((byte) 1));

        // 根据 typeCode 查询对应的字典项
        LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<>();
        List<SysDictItem> dictItems = sysDictItemMapper.selectList(queryWrapper.eq(SysDictItem::getTypeId, type.getDictTypeId()));
        List<SysDictItemVO> itemVOs = dictItems.stream().map(item -> {
            SysDictItemVO itemVO = new SysDictItemVO();
            BeanUtils.copyProperties(item, itemVO);
            return itemVO;
        }).collect(Collectors.toList());

        vo.setItems(itemVOs);
        return vo;
    }
}
